import os.path
import time

import allure
import yaml
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from po.utils.log_utils import logger


class BasePage:
    def __init__(self, driver: WebDriver = None):
        if driver is None:
            self.driver = webdriver.Chrome()
            self.driver.maximize_window()
            self.driver.implicitly_wait(10)
        else:
            self.driver = driver

    # def find_ele_click(self, by, locate):
    #     self.find_ele(by, locate).click()

    def find_ele(self, by, locate):
        """找一个元素"""
        try:
            ele = self.driver.find_element(by, locate)
        except Exception as e:
            ele = None
            # 保存截图
            self.screen_image()
            logger.info(f"元素{locate}未找到，具体错误信息为{e}")
        return ele

    def find_eles(self, by, locate):
        try:
            eles = self.driver.find_elements(by, locate)
        except Exception as e:
            eles = None
            logger.info(f"元素{locate}未找到，具体错误信息为{e}")
        return eles

    def open_url(self, url):
        self.driver.get(url)

    def wait_locate(self, by, locate, timeout=10):
        ele = WebDriverWait(self.driver, timeout).until(
            expected_conditions.presence_of_element_located((by, locate)))
        return ele

    def login_by_cookie(self):
        cookies = yaml.safe_load(open("../data/cookies.yaml", "r"))
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        self.driver.refresh()

    def close_browser(self):
        self.driver.quit()

    def  get_path(self, path_name):
        """获取绝对路径"""
        # 获取当前工具文件所在的路径
        root_path = os.path.dirname(os.path.abspath(__file__))
        # 拼接当前要输出日志的路径
        dir_path = os.sep.join([root_path, '..', f'/{path_name}'])
        return dir_path

    def screen_image(self):
        """截图"""
        # 截图名称
        now_time = time.strftime('%Y_%m_%d_%H_%M_%S')
        image_name = f"{now_time}.png"
        # 拼接截图保存路径
        # windows f"{self.get_path('image')}\\{image_name}"
        image_path = f"{self.get_path('image')}/{image_name}"
        logger.info(f"截图保存路径为{image_path}")
        # 截图
        self.driver.save_screenshot(image_path)
        allure.attach.file(image_path, name='image_name', attachment_type=allure.attachment_type.PNG)
        return image_path

    def save_page_source(self):
        """
        保存页面源码
        :return: 页面源码保存路径
        """
        # 文件命名
        now_time = time.strftime('%Y_%m_%d_%H_%M_%S')
        pagesource_name = f"{now_time}_pagesource.html"
        # 拼接文件保存路径
        # windows f"{self.get_path('pagesource')}\\{pagesource_name}"
        pagesource_path = f"{self.get_path('pagesource')}/{pagesource_name}"
        logger.info(f"页面源码文件保存路径为{pagesource_path}")
        # 保存 page source
        with open(pagesource_path, 'w', encoding='utf8') as f:
            f.write(self.driver.page_source)
        return pagesource_path

